﻿using EasyFileSync.Core;
using EasyFileSync.Core.Config;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace EasyFileSync
{
    class Program
    {
        static void Main(string[] args)
        {
            var sw = new Stopwatch();
            sw.Start();
            try
            {
                var configName = "sync.xml";
                WriteLine("加载配置中...");
                var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configName);
                if (!File.Exists(configPath))
                {
                    WriteLine($"未检测到配置文件：{configName}");
                    return;
                }

                var jobs = new List<SyncJob>();
                var config = new SyncConfig();
                config.Load(configPath);
                foreach (var job in config.Jobs)
                    jobs.Add(new SyncJob(job));
                WriteLine($"加载配置完成，同步任务 {jobs.Count} 项...");

                WriteLine("====================");
                Parallel.ForEach(jobs, job =>
                {
                    try
                    {
                        job.OutStream += WriteLine;
                        job.Start();
                    }
                    catch (Exception ex)
                    {
                        WriteLine($"Job：{job.Config.Name} 同步发生异常：{ex}");
                    }
                });
                WriteLine($"全部任务同步完成。");

            }
            catch (Exception ex)
            {
                Console.WriteLine();
                WriteLine(ex.ToString());
            }
            finally
            {
                sw.Stop();
                WriteLine("====================");
                WriteLine($"总耗时：{sw.Elapsed.TotalMilliseconds}ms.");
                Console.WriteLine();
                Console.WriteLine("按任意键退出...");
                Console.ReadKey();
            }

        }


        static void WriteLine(string output)
        {
            Console.WriteLine($"{DateTime.Now}> {output}");
        }
    }
}
